<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 朋友圈模型
 *
 * @author khj
 */
class ConsumerFriendsCircleModel extends MY_Model{

	public $tbFriends = 'consumer_friends_circle';
	public $tbPraise = 'consumer_friends_praise';
	public $tbComment = 'consumer_friends_comment';
    public $tbUser = 'consumer';

    /**
     * 获取列表数据
     * @return 	array
     * @author khj
     */
    public function adminPcGetList(){
        $consumer = trim(get('consumer')); // 所属用户
        $content = trim(get('c_content')); // 内容
        $address = trim(get('c_address')); // 地址
        $status = (int)get('c_status'); // 状态 1 隐藏 2 显示

        $star = strtotime(get('c_send_date_from'));
        $end = strtotime(get('c_send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if($consumer){
            $this->db->like(array('c.nickname' => $consumer));
        }
        if($content){
            $this->db->like(array('f.content' => $content));
        }
        if($address){
            $this->db->like(array('f.address' => $address));
        }
        if($status){
            $this->db->where(array('f.status' => $status));
        }
        if($star){
            $this->db->where('f.addtime >=', $star);
        }
        if($end){
            $this->db->where('f.addtime <= ', strtotime('+1day', $end));
        }

        if ($iSortCol_0 == 4){
            $this->db->order_by('f.browse_number', $sSortDir_0);
        }else if ($iSortCol_0 == 6){
            $this->db->order_by('f.addtime', $sSortDir_0);
        }else{
            $this->db->order_by('f.addtime', 'desc');
        }

        $this->db->select('f.id,f.content,f.latitude,f.longitude,f.address,f.browse_number,f.status,f.addtime,
        c.nickname as consumer')
            ->join($this->tbUser.' c', 'f.consumer_id=c.id')
            ->where('is_delete is null');
        $data = $this->pagination($this->tbFriends.' f');
        return  $data;
    }

	/**
	 * 保存信息
	 * @param 	array 	$data
	 * @param   integer $id
	 * @return	boolean|integer
	 * @return	boolean|integer
	 * @author khj
	 */
	public function save($data, $id = 0, $video = ''){
	    if($id){
	        $this->db->where('id', $id);
	        return $this->update($this->tbFriends, $data);
	    }elseif ($video){
            $this->db->where('video', $video);
            return $this->update($this->tbFriends, $data);
        }
	
	    return $this->insert($this->tbFriends, $data);
	}

    /**
     * 删除我的动态
     * @param string $fid  动态id
     * @param int $consumerId
     * @return bool
     */
	public function deleteCircle($fid, $consumerId){
	    if(!$fid || !$consumerId)return false;
	    $this->db->where(array('id' => $fid,'consumer_id' => $consumerId));

	    return $this->delete($this->tbFriends);
    }

    /**
     * 获取状态
     *
     * @param	integer	$key
     * @param	boolean	$show	是否显示
     * @return	mixed
     */
    public function getStatus($key = null, $show = false){

        $config = array(
            1 => '隐藏',
            2 => '显示',
        );

        if($key !== null){

            if(isset($config[$key]) && ! $show){
                return $config[$key];
            }

            if(isset($config[$key]) && $show){

                if($key == 1){
                    return '<span class="label label-danger">'.$config[$key].'</span>';
                }else if($key == 2){
                    return '<span class="label label-success">'.$config[$key].'</span>';
                }
            }
            return '';
        }

        return $config;
    }

    /**
     * 保存评论信息
     * @param 	array 	$data
     * @param   integer $id   评论id
     * @return	boolean|integer
     * @author khj
     */
    public function saveComment($data, $id = 0){
        if($id){
            $this->db->where('id', $id);
            return $this->update($this->tbComment, $data);
        }

        return $this->insert($this->tbComment, $data);
    }

    /**
     * 点赞
     * @param $data
     *
     * @return bool|int
     */
	public function savePraise($data){

	    return $this->insert($this->tbPraise, $data);
	}

    /**
     * 取消点赞
     * @param $fid     朋友圈id
     * @param $consumerId  消费者id
     * @param $type   1买家秀 2卖家秀
     * @return bool|int
     */
    public function deletePraise($fid, $consumerId, $type = 1,$user_type = 1){
        if(!$fid || !$consumerId)return false;

        $this->db->where(array('fid' => $fid,'consumer_id' => $consumerId,'type' => $type,'user_type' => $user_type));

        return $this->delete($this->tbPraise);
    }

    /**
     * 获取动态详情
     * @param $id    int    动态id
     * @param $relationId = $consumer_id |$merchant_id       发布者id
     * @param $type   1买家秀 2卖家秀
     * @param bool $mini
     * @param int       $consumerId  消费者id
     * @return array
     */
	public function getInfo($id, $type = 1, $relationId = 0, $mini = false, $consumerId = 0){

	    if(!$id)return array();


        if($type == 1){//买家秀
            if($relationId){
                $this->db->where('f.consumer_id', $relationId);
            }

            if($mini){
                $this->db->select('f.id,f.address,f.status,f.browse_number')
                    ->where('f.id', $id);
                return $this->getOne($this->tbFriends.' f');
            }else{
                $this->db->select('f.id,f.consumer_id,f.video,f.image,f.content,f.latitude,f.longitude,f.address,f.browse_number,f.addtime,
                        f.yun_status,u.portrait,u.nickname,f.status,p.fid as praise')
                    ->join($this->tbUser.' u', 'u.id = f.consumer_id')
                    ->join($this->tbPraise.' p', 'p.fid = f.id and p.type = '.$type.' and p.consumer_id = '.$consumerId, 'left')
                    ->where('f.id', $id);
            }

            $tA = $this->getOne($this->tbFriends.' f');
        }else{//卖家秀
            if($relationId){
                $this->db->where('f.merchant_id', $relationId);
            }
            get_instance()->loadModel('MerchantFriendsCircleModel','mMerFriends','merchant');
            if($mini){
                $this->db->select('f.id,f.address,f.status,f.browse_number')
                    ->where('f.id', $id);
                return $this->getOne($this->mMerFriends->tbFriends.' f');
            }else{
                $this->db->select('f.id,f.merchant_id,f.video,f.image,f.content,f.latitude,f.longitude,f.address,f.browse_number,f.addtime,
                        f.yun_status,u.portrait,f.status,s.shop_name as nickname,p.fid as praise')
                    ->join($this->mMerFriends->tbUser.' u', 'u.id = f.merchant_id')
                    ->join($this->tbPraise.' p', 'p.fid = f.id and p.type = '.$type.' and p.consumer_id = '.$consumerId, 'left')
                    ->join($this->mMerFriends->tbShop.' s', 's.merchant_id = f.merchant_id')
                    ->where('f.id', $id);
            }

            $tA = $this->getOne($this->mMerFriends->tbFriends.' f');
        }

        $tA['addtime'] = showBeautifulTimeForMat($tA['addtime']);
        $tA['praise'] = $tA['praise'] ? '1':'0';//1已点赞 0未点赞
        $tA['content'] = $tA['content'] ? base64_decode($tA['content']):'';
        $tA['portrait'] = $tA['portrait'] ? getImage($tA['portrait']):getDefaultPortrait(1);
        $tA['video'] = $tA['video'] ? $tA['video']:'';
        $tA['status_str'] = $this->getStatus($tA['status'], true);
        //图片
        $image = array();
        if($tA['image']){
            $tA['image'] = json_decode($tA['image']);
            foreach ($tA['image'] as $mg){
                $image[] = getImage($mg);
            }
        }
        $tA['image'] = $image;
        return $tA;
    }

    /**
     * 获取评论列表数据
     * @return 	array
     */
    public function adminPcGetCommentsList(){
        $id = (int)get('id');
        $type = trim(get('type')); // 所属用户
        if (!$id){
            return array();
        }
        if ($type != 'consumer' && $type != 'merchant'){
            return array();
        }
        $consumer = trim(get('consumer')); // 所属用户
        $content = trim(get('content')); // 内容
        $star = strtotime(get('send_date_from'));
        $end = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($id){
            $this->db->where(array('c.fid' => $id));
        }
        if ($type){
            $type = $type == 'merchant' ? 2 : 1;
            $this->db->where(array('c.type' => $type));
        }
        if($consumer){
            $this->db->like(array('u.nickname' => $consumer));
        }
        if($content){
            $this->db->like(array('c.content' => $content));
        }
        if($star){
            $this->db->where('c.addtime >=', $star);
        }
        if($end){
            $this->db->where('c.addtime <= ', strtotime('+1day', $end));
        }

        if ($iSortCol_0 == 3){
            $this->db->order_by('c.addtime', $sSortDir_0);
        }else{
            $this->db->order_by('c.addtime', 'desc');
        }

        $this->db->select('c.id,c.fid,c.content,c.parent_name,c.addtime,u.nickname as consumer')
            ->join($this->tbUser.' u', 'c.consumer_id=u.id');
        $data = $this->pagination($this->tbComment.' c');
        return  $data;
    }

    /**
     * 获取动态评论列表
     * @param $fid  动态id
     * @param $type  1买家秀 2卖家秀
     * @return array
     */
    public function getAllComments($fid, $type){

	    if(!$fid)return array();
        get_instance()->loadModel('MerchantFriendsCircleModel','mMerFriends','merchant');

	    $this->db->select('c.id,c.consumer_id,c.content,c.parent_name,c.addtime,c.user_type,u.portrait,u.nickname,
	                        mu.nickname as shop_name,mu.portrait as shop_portrait')
                 ->join($this->tbUser.' u','u.id = c.consumer_id and c.user_type = 1', 'left')
                 ->join($this->mMerFriends->tbUser.' mu','mu.id = c.consumer_id and c.user_type = 2', 'left')

                 ->where(array('c.type' => $type,'c.fid' => $fid));
	    if ($type == 1){
	        $this->db->join($this->tbFriends.' f','f.id = c.fid');
        }else{
            get_instance()->loadModel('MerchantFriendsCircleModel','mMerFriends','merchant');
            $this->db->join($this->mMerFriends->tbFriends.' f','f.id = c.fid');
        }
	    $tA = $this->getAll($this->tbComment.' c');
	    if($tA){
	        foreach ($tA as $k=>&$v){
	            $v['content'] = base64_decode($v['content']);
	            $v['parent_name'] = $v['parent_name']?$v['parent_name']:'';
                $v['addtime'] = showBeautifulTimeForMat($v['addtime']);
                if($v['user_type'] == 2){
                    $v['portrait'] = $v['shop_portrait'];
                    $v['nickname'] = $v['shop_name'];
                }
                $v['portrait'] = $v['portrait'] ? getImage($v['portrait']):getDefaultPortrait(1);
                unset($v['shop_name'],$v['shop_portrait'],$v['user_type']);
            }
        }

        return $tA;
    }

    /**
     * 获取点赞列表数据
     * @return 	array
     */
    public function adminPcGetPraiseList(){
        $id = (int)get('id');
        $type = trim(get('type')); // 所属用户
        if (!$id){
            return array();
        }
        if ($type != 'consumer' && $type != 'merchant'){
            return array();
        }
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"
        if ($iSortCol_0 == 1){
            $this->db->order_by('p.addtime', $sSortDir_0);
        }else{
            $this->db->order_by('p.addtime', 'desc');
        }

        $this->db->select('p.addtime,u.nickname as consumer')
            ->join($this->tbUser.' u', 'p.consumer_id=u.id');
        $data = $this->pagination($this->tbPraise.' p');
        return  $data;
    }

    /**
     * 获取动态点赞列表
     * @param $fid  动态id
     * @param $type  1买家秀 2卖家秀
     * @return array
     */
    public function getAllPraise($fid, $type, $limit = 0){
        if(!$fid)return array();
        $count = 0;
        if($limit){
            //总点赞数量
            $this->db->where(array('type' => $type,'fid' => $fid));
            $count = $this ->count($this->tbPraise);

            $this->db->limit($limit);

        }
        get_instance()->loadModel('MerchantFriendsCircleModel','mMerFriends','merchant');
        if($type == 1){
            $this->db->join($this->tbFriends.' f','f.id = p.fid');
        }else{
            $this->db->join($this->mMerFriends->tbFriends.' f','f.id = p.fid');
        }
        $this->db->select('p.consumer_id,p.addtime,u.nickname,u.portrait,p.user_type,
                            s.shop_name,mu.portrait as shop_portrait')
            ->join($this->tbUser.' u','u.id = p.consumer_id and p.user_type = 1', 'left')
            ->join($this->mMerFriends->tbUser.' mu','mu.id = p.consumer_id and p.user_type = 2', 'left')
            ->join($this->mMerFriends->tbShop.' s','s.merchant_id = p.consumer_id and p.user_type = 2', 'left')
            ->where(array('p.type' => $type,'p.fid' => $fid));

        $tA = $this->getAll($this->tbPraise.' p');

        if($tA){
            foreach ($tA as $k=>&$v){

                if($v['user_type'] == 2){
                    $v['portrait'] = $v['shop_portrait'];
                    $v['nickname'] = $v['shop_name'];
                }
                $v['portrait'] = $v['portrait'] ? getImage($v['portrait']):getDefaultPortrait(1);
                unset($v['shop_name'],$v['shop_portrait'],$v['user_type']);
            }
        }
        $Data = array(
            'list' => $tA,
            'count' => $count
        );
        return $Data;
    }

    /**
     * 获取单条评论信息
     * @param $id
     * @return array
     */
    public function getCommentInfo($id){
	    if(!$id)return array();
	    $this->db->select('fid')
                 ->where('id', $id);

	    return $this->getOne($this->tbComment);
    }

    /**
     * 获取朋友圈列表
     * @param $page   int       页码
     * @param $type   int       1买家秀 2卖家秀
     * @param $consumerId   int     消费者id
     * @param $relationId = $consumerId|$merchantId  发布者id
     * @return array
     */
    public function appGetFriendsCircleList($page, $type = 1, $consumerId = 0,$relationId = 0){

        if($type == 1){
            if($relationId){
                $this->db->where('f.consumer_id', $relationId);
            }
            if(!$relationId || $consumerId != $relationId){
                $this->db->where('f.status', 2);
            }
            $this->db->select('f.id,f.consumer_id,f.video,f.image,f.content,f.latitude,f.longitude,f.address,f.browse_number,f.addtime,
                        u.portrait,u.nickname,p.fid as praise')
                ->join($this->tbUser.' u', 'u.id = f.consumer_id')
                ->join($this->tbPraise.' p', 'p.fid = f.id and p.type = '.$type.' and p.consumer_id = '.$consumerId, 'left')
                ->group_by('f.id')
                ->order_by('f.addtime desc')
                ->where('f.status', 2)
                ->where('f.yun_status', 2);

            $tA = $this->appPage($this->tbFriends.' f', $page, true);

        }else{
            if($relationId){
                $this->db->where('f.merchant_id', $relationId);
            }
            if(!$relationId || $consumerId != $relationId){
                $this->db->where('f.status', 2);
            }
            get_instance()->loadModel('MerchantFriendsCircleModel','mMerFriends','merchant');
            $this->db->select('f.id,f.merchant_id,f.video,f.image,f.content,f.latitude,f.longitude,f.address,f.browse_number,f.addtime,
                        u.portrait,u.nickname,p.fid as praise')
                ->join($this->mMerFriends->tbUser.' u', 'u.id = f.merchant_id')
                ->join($this->tbPraise.' p', 'p.fid = f.id and p.type = '.$type.' and p.consumer_id = '.$consumerId, 'left')
                ->group_by('f.id')
                ->order_by('f.addtime desc')
                ->where('f.yun_status', 2);

            $tA = $this->appPage($this->mMerFriends->tbFriends.' f', $page, true);

        }
//        echo $this->db->last_query();
        $fids = array();
        foreach ($tA['list'] as $k=>&$v){
            if(!in_array($v['id'], $fids)){
                $fids[] = $v['id'];
            }
            $v['addtime'] = showBeautifulTimeForMat($v['addtime']);
            $v['praise'] = $v['praise'] ? '1':'0';//1已点赞 0未点赞
            $v['content'] = $v['content'] ? base64_decode($v['content']):'';
            $v['nickname'] = $v['nickname'] ? $v['nickname']:'暂无昵称';
            $v['portrait'] = $v['portrait'] ? getImage($v['portrait']):getDefaultPortrait(1);
            $v['video'] = $v['video'] ? $v['video']:'';
            //图片
            $image = array();
            if($v['image']){
                $v['image'] = json_decode($v['image']);
                foreach ($v['image'] as $mg){
                    $image[] = getImage($mg);
                }
            }
            $v['image'] = $image;
        }
        if($fids){
            //获取点赞总数量
            $this->db->select('count(fid) as number,fid')
                     ->where('type', $type)
                     ->where_in('fid', $fids)
                     ->group_by('fid');
            $praiseCount = $this->getAll($this->tbPraise);

            foreach ($praiseCount as $p){
                $praiseCount[$p['fid']] = $p;
            }

            foreach ($tA['list'] as $key=>$value){
                $count = isset($praiseCount[$value['id']])?$praiseCount[$value['id']]['number']:'0';
                $tA['list'][$key]['praise_count'] = $count < 100 ? $count:'99+';
            }
        }


        return $tA;
    }

    /**
     * 判断是否点赞过
     * @param $fid  朋友圈id
     * @param $consumerId  消费者id
     * @param $type   1买家秀 2卖家秀
     * @param $user_type   1消费者  2商家
     * @return bool
     */
    public function praiseIsExist($fid, $consumerId, $type = 1, $user_type = 1){

        if( ! $fid || !$consumerId) return false;

        $this->db->select('fid')->where(array('fid' => $fid, 'consumer_id' => $consumerId,'type' => $type));

        $tA = $this->getOne($this->tbPraise);
        if($tA){
            return $tA['fid'];
        }

        return false;
    }

    /**
     * 获取我发布的条数
     * @param $userId
     * @return array
     * @author heyu
     */
    public function getTotal($userId){
        $this->db->where(array('consumer_id' => $userId, 'yun_status' => 2, 'status' => 2));
        return $this->count($this->tbFriends);

    }
}